﻿using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;

using SRM.Application.PageResult.IServices;
using SRM.Application.PageResult.PurchaseOrderPage;
using SRM.Application.PageResult.ReturnOrderPage;
using SRM.Core.Extension;
using SRM.Core.Models;
using SRM.Core.Models.Base;
using SRM.Core.Repositories;
using SRM.Core.Utility;
using SRM.WebSite.Models;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace SRM.WebSite.Controllers
{
    public class DeliverOrderController : Controller
    {
        private readonly IDeliverOrderServer _deliverOrderServer;
        private readonly IDeliverOrderDtlServer _deliverOrderDtlServer;
        private readonly IRepository<DeliverOrder> _deliverOrderRepository;
        private readonly IRepository<DeliverOrderDetail> _deliverDtlRepository;
        private readonly IRepository<ReturnOrder> _returnOrderRepository;
        private readonly IRepository<ReturnOrderDetail> _returnOrderDtlRepository;
        private readonly IRepository<PurchaseOrder> _purchaseOrderRepository;

        public DeliverOrderController(
            IDeliverOrderServer deliverOrderServer,
            IDeliverOrderDtlServer deliverOrderDtlServer, IRepository<DeliverOrder> repositoryDeliverOrderRepository, IRepository<DeliverOrderDetail> repositoryDeliverDtlRepository, IRepository<ReturnOrder> returnOrderRepository, IRepository<PurchaseOrder> purchaseOrderRepository, IRepository<ReturnOrderDetail> returnOrderDtlRepository)
        {
            _deliverOrderServer = deliverOrderServer;
            _deliverOrderDtlServer = deliverOrderDtlServer;
            _deliverOrderRepository = repositoryDeliverOrderRepository;
            _deliverDtlRepository = repositoryDeliverDtlRepository;
            _returnOrderRepository = returnOrderRepository;
            _purchaseOrderRepository = purchaseOrderRepository;
            _returnOrderDtlRepository = returnOrderDtlRepository;
        }

        public async Task<IActionResult> Index(PagerModelInput input)
        {
            var list = await _deliverOrderServer.GetDeliverOrderList(input);
            return View(list);
        }

        public async Task<IActionResult> PreviewDeliver(int Id)
        {
            var list = await _deliverDtlRepository.GetAllListAsync(p => p.DeliverOrderId == Id);
            return View(list);
        }

        public async Task<IActionResult> DeliverDtl(PagerModelInput input)
        {
            var list = await _deliverOrderDtlServer.GetDeliverOrderDtl(input);
            return View(list);
        }

        public async Task<IActionResult> DeliverOrderReview()
        {
            if (ModelState.IsValid)
            {
                var action = Request.Form["action"].ToString();
                var Ids = Request.Form["Ids"].ToString();
                List<int> IdList = CompilerExt.ConverToList(Ids);
                var deliverOrderList = await _deliverOrderRepository.GetAllListAsync(r => IdList.Contains(r.Id));
                if (deliverOrderList == null || deliverOrderList.Count == 0)
                {
                    ViewBag.ErrorMessage = $"送货ID的信息不存在，请刷新重试。";
                    return View("Error");
                }
                var executeAction = (ExecuteActionEnum)Enum.Parse(typeof(ExecuteActionEnum), action);
                DeliverOrderStateEnum? @enum = null;
                string error = "";
                switch (executeAction)
                {
                    case ExecuteActionEnum.审核:
                        deliverOrderList.ForEach(r =>
                        {
                            if (r.ReviewState != DeliverOrderStateEnum.未审核)
                            {
                                error = $"选择的送货单数据状态存在不为{DeliverOrderStateEnum.未审核}的订单，操作失败！";
                                return;
                            }
                            @enum = DeliverOrderStateEnum.已审核;
                        });
                        break;

                    case ExecuteActionEnum.撤销审核:
                        deliverOrderList.ForEach(r =>
                        {
                            if (r.ReviewState != DeliverOrderStateEnum.已审核)
                            {
                                error = $"选择的送货单数据状态存在不为{DeliverOrderStateEnum.已审核}的订单，操作失败！";
                                return;
                            }
                            @enum = DeliverOrderStateEnum.未审核;
                        });
                        break;

                    case ExecuteActionEnum.转质检:
                        deliverOrderList.ForEach(r =>
                        {
                            if (r.ReviewState != DeliverOrderStateEnum.已审核)
                            {
                                error = $"选择的送货单数据状态存在不为{DeliverOrderStateEnum.已审核}的订单，操作失败！";
                                return;
                            }
                            @enum = DeliverOrderStateEnum.质检合格;
                        });
                        break;
                }
                if (string.IsNullOrEmpty(error) && @enum.HasValue)
                {
                    for (int i = 0; i < deliverOrderList.Count; i++)
                    {
                        deliverOrderList[i].ReviewState = @enum.Value;
                        if (@enum.Value == DeliverOrderStateEnum.未审核)
                        {
                            deliverOrderList[i].ReviewBy = "";
                            deliverOrderList[i].ReviewDate = null;
                        }
                        else
                        {
                            deliverOrderList[i].ReviewBy = LoginUser.LoginUsers.UserName;
                            deliverOrderList[i].ReviewDate = DateTime.Now;
                        }
                        await _deliverOrderRepository.UpdateAsync(deliverOrderList[i]);
                    }
                    return Json("ok:操作成功");
                }
                else
                {
                    return Json($"no:{error}");
                }
            }
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> DeliverOrderDel()
        {
            if (ModelState.IsValid)
            {
                var Ids = Request.Form["Ids"].ToString();
                List<int> IdList = CompilerExt.ConverToList(Ids);
                var deliverOrderLIst = await _deliverOrderRepository.GetAllListAsync(r => IdList.Contains(r.Id));
                if (deliverOrderLIst == null || deliverOrderLIst.Count == 0)
                {
                    ViewBag.ErrorMessage = $"送货ID的信息不存在，请刷新重试。";
                    return View("Error");
                }
                for (int i = 0; i < deliverOrderLIst.Count; i++)
                {
                    var details =
                        await _deliverDtlRepository.GetAllListAsync(d => d.DeliverOrderId == deliverOrderLIst[i].Id);
                    for (int j = 0; j < details.Count; j++)
                    {
                        await _deliverDtlRepository.DeleteAsync(details[j]);
                    }

                    await _deliverOrderRepository.DeleteAsync(deliverOrderLIst[i]);
                }
                return Json("ok:操作成功");
            }
            return Json($"no:删除失败，请重试！");
        }

        [HttpGet]
        public async Task<IActionResult> DeliverOrderEdit(int? Id)
        {
            DeliverOrderViewModel model = new DeliverOrderViewModel();
            int? purchaseOrderId = null;
            int? returnOrderId = null;
            ViewBag.Title = "送货单新增";
            if (Id.HasValue)
            {
                ViewBag.Title = "送货单修改";

                DeliverOrder deliverOrder =
                    await _deliverOrderRepository.FirstOrDefaultAsync(r => r.Id == Id.Value);

                CompilerExt.AutoMapping(deliverOrder, model);
                purchaseOrderId = deliverOrder.PurchaseOrderId;
                returnOrderId = deliverOrder.ReturnOrderId;
            }

            model.ReturnOrderList = ReturnOrdersDropDownList(returnOrderId);
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> DeliverOrderEdit(DeliverOrderViewModel input)
        {
            if (ModelState.IsValid)
            {
                bool IsEdit = input.Id > 0;
                ReturnOrder returnOrder = await _returnOrderRepository.FirstOrDefaultAsync(p => p.Id == input.ReturnOrderId);
                if (returnOrder == null)
                {
                    ViewBag.ErrorMessage = $"回货单的信息ID为{input.Id}的信息不存在，请重试。";
                    return View("Error", ViewBag.ErrorMessage);
                }

                PurchaseOrder purchaseOrder = await _purchaseOrderRepository.FirstOrDefaultAsync(p => p.Id == returnOrder.PurchaseOrderId);

                DeliverOrder model;

                if (!IsEdit)
                    model = new DeliverOrder();
                else
                    model = await _deliverOrderRepository.FirstOrDefaultAsync(r => r.Id == input.Id);

                model.ItemCode = input.ItemCode;
                model.ItemName = input.ItemName;
                model.Remark = input.Remark;
                model.OrderType = returnOrder.OrderType;

                model.ReturnOrderId = returnOrder.Id;
                model.ReturnOrder = returnOrder;
                if (purchaseOrder == null || string.IsNullOrEmpty(purchaseOrder?.PurchaseOrderNo))
                {
                    purchaseOrder = new PurchaseOrder();
                    model.PurchaseOrderId = 0;
                }
                model.PurchaseOrderId = purchaseOrder.Id;
                model.PurchaseOrder = purchaseOrder;

                if (!IsEdit)
                {
                    model.CreateBy = User.Identity.Name;
                    model.CreateDate = DateTime.Now;
                    model.DeliverOrderNo = "D" + SecurityHelper.GeneratePassword(6).ToUpper();
                    model.ReviewBy = null;
                    model.ReviewDate = null;
                    model.ReviewState = DeliverOrderStateEnum.未审核;
                    model.SupplierId = LoginUser.LoginUsers.SupplierId;
                }

                var deliverOrderDetail =
                    await _deliverDtlRepository.GetAllListAsync(d => d.DeliverOrderId == model.Id);

                DeliverOrder deliverOrder;
                if (IsEdit)
                {
                    foreach (var item in deliverOrderDetail)
                    {
                        await _deliverDtlRepository.DeleteAsync(item);
                    }
                    deliverOrder = await _deliverOrderRepository.UpdateAsync(model);
                }
                else
                {
                    deliverOrder = await _deliverOrderRepository.InsertAsync(model);
                }

                List<DeliverOrderDetail> deliverOrderDetails =
                    await AddReturnOrderDetail(deliverOrder.Id, returnOrder.Id);

                for (int i = 0; i < deliverOrderDetails.Count; i++)
                {
                    await _deliverDtlRepository.InsertAsync(deliverOrderDetails[i]);
                }
                return RedirectToAction(nameof(Index));
            }
            return View(input);
        }

        [NonAction]
        private SelectListItem[] ReturnOrdersDropDownList(int? returnOrderId)
        {
            var roList = _returnOrderRepository.GetAll();
            if (!LoginUser.LoginUsers.IsHQ)
            {
                roList = roList.Where(r => r.SupplierId == LoginUser.LoginUsers.SupplierId);
            }
            roList = roList.Where(r => r.ReviewState == ReturnOrderStateEnum.已复审);

            var returnOrders = roList.AsNoTracking().OrderBy(r => r.Id).ToList();

            SelectListItem[] selectList = new SelectListItem[returnOrders.Count];
            for (int i = 0; i < returnOrders.Count; i++)
            {
                var item = returnOrders[i];
                SelectListItem select = new SelectListItem();
                select.Text = item.ReturnOrderNo;
                select.Value = item.Id.ToString();
                if (returnOrderId.HasValue && item.Id == returnOrderId.Value)
                {
                    select.Selected = true;
                }
                selectList[i] = select;
            }
            return selectList;
        }

        [NonAction]
        private async Task<List<DeliverOrderDetail>> AddReturnOrderDetail(int deliverOrderId, int returnOrderId)
        {
            List<DeliverOrderDetail> details = new List<DeliverOrderDetail>();
            var returnOrderDtl = await _returnOrderDtlRepository.GetAllListAsync(p => p.ReturnOrderId == returnOrderId);
            foreach (var item in returnOrderDtl)
            {
                DeliverOrderDetail detail = new DeliverOrderDetail()
                {
                    DeliverOrderId = deliverOrderId,
                    Code = item.Code,
                    Name = item.Name,
                    Spec = item.Spec,
                    Color = item.Color,
                    Material = item.Material,
                    Price = item.Price,
                    Currency = item.Currency,
                    NetFinallyPriceFC = item.NetFinallyPriceFC,
                    TaxRate = item.TaxRate,
                    Remark = item.Remark,
                    Receiving = null,
                    Phone = null,
                    Address = null,
                    IsLiquidation = false,
                    LiquidationType = LiquidationTypeEnum.电子账户
                };
                details.Add(detail);
            }
            return details;
        }
    }
}
